function [GG,RR,Cobs,eu,SDX,ZZ,initss,ssvec,flag,ssnames,namesstates,namesshocks,GAM0,GAM1,PSI,PPI] =...
    modSE_modver01(param,~,addsol)
%{
    Inputs:
    \begin{itemize}
    \item |param| Parameter Vector
    \item |~| (Currently Unused)
    \item |addsol| Additional settings
    \end{itemize}
    
    Outputs:
    \begin{itemize}
    \item |GG| Coefficient Matrix on Lagged Endogenous Variables
    \item |RR| Coefficient Matrix on Exogenous Shocks
    \item |Cobs| Vector of Constants
    \item |eu| Existence and Uniqueness
    \item |SDX| Standard Deviations of Exogenous Shocks
    \item |ZZ| Coefficient Matrix on Observables
    \item |initss| (Currently Unused)
    \item |ssvec| Values of Important Steady-State Variables
    \item |flag| Important Flags
    \item |ssnames| Names of Steady-State Values
    \item |namesstates| Names of States
    \item |namesshocks| Names of Shocks
    \item |ACont| Coefficient Matrix on Contemporaneous Endogenous
    Variables (Useful for Debugging)
    \item |ALag| Coefficient Matrix on Lagged Endogenous Variables (Useful
    for Debugging)
    \item |ALead| Coefficient Matrix on Lead Endogenous Variables (Useful
    for Debugging)
    \item |PSI| Coefficient Matrix on Exogenous Variables (Useful for
    Debugging)
    \end{itemize}
    %}
    
    initss  = [];     ssvec   = [];
    
    flag.ssok   = 1;    % Steady-State OK (Not Changed in this Model)
    flag.solver = 1;    % Which Solver to Use (Not Change in this model)
    
    % =========================================================================
    %%  PART I: Parameters and Positions
    
    AD          = param(1);     % average Duration of Government Debt
    bet         = param(2);     % discount factor
    delt        = param(3);     % private capital depreciation rate
    alph        = param(4);     % share of capital in the prod. function
    etaw        = param(5);     % elasticity of substitution b/w labor talents
    etap        = param(6);     % elasticity of substitution b/w intermediate goods
    sgc         = param(7);     % steady state government consumption to model Y ratio;
    sb          = param(8);     % steady state government debt to model Y ratio
    taul        = param(9);     % steady state labor tax rate
    tauk        = param(10);    % steady state capital tax rate
    tauc        = param(11);    % steady state consumption tax rate
    gamm100     = param(12);    % steady state growth rate of technology, multiplied by 100
    pistar100   = param(13);
    xi          = param(14);    % inverse Frisch elasticity
    muHH        = param(15);    % fraction of non-savers in population
    omegaw      = param(16);    % prob. of unions not resetting price
    omegap      = param(17);    % prob. of firms not resetting price
    gpsi        = param(18);    % K utilization cost parameter
    s           = param(19);    % s" in the investment adjustment cost function
    chiw        = param(20);    % percentage of unions' wage adjustment when they cannot optimize
    chip        = param(21);    % percentage of intermediate firms' price adjustment when they cannot optimize
    thet        = param(22);    % habit formation
    alphag      = param(23);    % substitutability (>0) or complementarity (< 0) of private and public consumption
    
    phipi       = param(24);    % Taylor rule inflation coefficient
    phiy        = param(25);    % Taylor rule output coefficient
    %    phipic      = param(26);    % Taylor rule inflation coefficient COUNTERFACTUAL ECONOMY
    signEff     =1;             % if 1, fiscal tools play the role of signals
    gammgc      = param(27);    % response of government consumption to debt
    gammtk      = param(28);    % response of capital tax to debt
    gammtl      = param(29);    % response of labor tax to debt
    gammtc      = param(30);    % response of consumption tax to debt
    gammz       = param(31);    % response of saver transfers to debt
    phizy       = param(32);    % Transfers response to GDP (automatic stabilizers)
    csi_rp      = param(33);    % Transfers response to future risk-premium shocks
    csi_a       = param(34);    % Transfers response to future tfp shocks
    %     gammgcc     = param(33);    % response of government consumption to debt COUNTERFACTUAL ECONOMY
    %     gammtkc     = param(34);    % response of capital tax to debt COUNTERFACTUAL ECONOMY
    %     gammtlc     = param(35);    % response of labor tax to debt COUNTERFACTUAL ECONOMY
    %     gammtcc     = param(36);    % response of consumtpion tax to debt COUNTERFACTUAL ECONOMY
    %     gammzc      = param(37);    % response of saver transfers to debt COUNTERFACTUAL ECONOMY
    %    nfrp        = param(38);      % Share of long-term transfer shocks affecting the counterfactual economy
    rhor        = param(35);    % serial correlation on interest rate in Taylor rule
    rhogc       = param(36);    % serial correlation on gov. consumption rule
    rhoz        = param(37);    % serial correlation on savers transfers rule
    rhotk       = param(38);    % serial correlation on capital tax rule
    rhotl       = param(39);    % serial correlation on labor tax rule
    rhotc       = param(40);    % serial correlation on consumption tax rule
    rhoeg       = param(41);    % AR coefficients on government consumption policy shocks
    rhoez       = param(42);    % AR coefficients on government transfers policy shocks
    rhozlr      = param(43);    % AR coefficients on government transfers policy shocks
    rhoa        = param(44);    % serial correlation on technological productivity growth
    rhob        = param(45);    % serial correlation on preference shock
    rhoem       = param(46);    % AR coefficients on monetary policy shocks
    rhoi        = param(47);    % serial correlation on investment preference shock
    rhow        = param(48);    % serial correlation on wage markup shock
    rhop        = param(49);    % serial correlation on price markup shock
    rhorp       = param(50);    % serial correlation risk premium shock
    rhopidrift  = param(51);    % serial correlation inflation drift
    
    %     ssR         = param(57); % 1 Shock Specicic Rules, else two seperate economies
    
    startParSTD=58;
    siggc       = param(startParSTD);  % gov. consumption shock standard deviation
    sigz        = param(startParSTD+1);  % saver transfer shock standard deviation
    sigzlr      = param(startParSTD+2);  % saver transfer shock standard deviation (long-run comp)
    siga        = param(startParSTD+3);    % technology shock standard deviation
    sigb        = param(startParSTD+4);  % preference shock standard deviation
    sigm        = param(startParSTD+5);  % monetary policy shock standard deviation
    sigi        = param(startParSTD+6);  % investment preference shock standard deviation
    sigw        = param(startParSTD+7);  % wage markup shock standard deviation
    sigp        = param(startParSTD+8);  % price markup shock standard deviation
    sigrp       = param(startParSTD+9);  % risk premium shock
    sigpistar   = param(startParSTD+10);  % shock to the inflation drift
    sigv        = param(startParSTD+11); % Measurement error govt
    STD_gdpME   = param(startParSTD+12);
    STD_byME    = param(startParSTD+13);
    flagEFFR    = param(startParSTD+14);
    
    startFG     = startParSTD+15;
    numSignal   = param(startFG);
    FG_loc      = linspace(1+startFG,1+startFG+(1+numSignal)*3,4);
    Aload       = param(FG_loc(1):FG_loc(2)-1);
    Bload       = param(FG_loc(2):FG_loc(3)-1);
    STD         = param(FG_loc(3):FG_loc(4)-1);
    FactA_STD   = param(max(FG_loc));
    FactB_STD   = param(max(FG_loc)+1);
    
    %%  PART II: Position of Variables
    
    csLog=1;         % consumption savers
    cnLog=2;         % consumption: Non-Savers
    RLog=3;          % nominal interest rate
    iLog=4;          % investment
    kLog=5;          % effective capital
    vLog=6;          % capital utilization rate
    lLog=7;          % labor
    yLog=8;          % output
    gcLog=9;         % govt consumption
    cLog=10;         % aggregate consumption
    qLog=11;         % Lagrangian multiplier for a unit of investment good
    rkLog=12;        % real return for private k
    wLog=13;         % real wage
    piLog=14;        % inflation
    bLog=15;         % govt debt
    sbLog=16;        % b/y ratio
    taukLog=17;      % tauk
    taulLog=18;      % taul
    taucLog=19;      % tauc
    rLog=20;         % real interest rate
    zLog=21;         % transfers total
    zlrLog=22;      % transfers LR
    mcLog=23;        % real marginal cost
    kbarLog=24;      % private capital
    lambdaLog=25;    % household Lagrangian multiplier from budget constraint
    PbLog=26;        % price of bonds
    cstarLog=27;     % consumption in utility function
    piLLog=28;       % long-run inflation
    rLLog=29;        % long-run interest rate
    rbLog=30;        % rb defined
    piLagLog=31;     % lagged inflation
    yLagLog=32;      % lagged output
    % Observable Variables (used for filtering)
    yobs=33;
    cobs=34;
    iobs=35;
    gobs=36;
    wobs=37;
    zobs=38;
    
    % AR exogenous processes
    startShocks = 39;
    shkgcLog     = startShocks;      %1  government consumption shock
    shkzLog      = startShocks+1;    %2  tranfer shock
    shkzLRLog    = startShocks+2;    %3  tranfer shock LR
    shkaLog      = startShocks+3;    %4  technology shock
    shkbLog      = startShocks+4;    %5  preference shock
    shkmLog      = startShocks+5;    %6  monetary policy shock
    shkiLog      = startShocks+6;    %7  investment specific technology shock
    shkwLog      = startShocks+7;    %8  wage markup shock
    shkpLog      = startShocks+8;    %9  price markup shock
    shkrpLog     = startShocks+9;    %10  risk premium shock
    shkpistarLog = startShocks+10;   %11  Inflation drift shock
    shkaTLog     = startShocks+11;   %13 next priod's tfp shock
    shka0Log     = startShocks+12;   %14 surprise tech shock
    shka1Log     = startShocks+13;   %15 anticipated tech shock
    shkrpTLog     = startShocks+14;  %16  next priod's risk premium shock
    shkrp0Log    = startShocks+15;   %17 surprise risk-premium shock
    shkrp1Log    = startShocks+16;   %18 anticipated risk-premium shock
    currentplace    = startShocks+16;
    
    
    % news shocks
    signalOrder={'one','two','three','four','five','six','seven','eight',...
        'nine','ten','eleven','twelve',...
        'thirteen','fourteen','fifteen','sixtheen','seventeen','eighteen','nineteen','twenty'};%,'twentyone'...
    %         ,'twentytwo','twentythree','twentyfour','twentyfive','twentysix','twentyseven','twentyeigh',...
    %         'twentynine','thirty','thirtyone'...
    %         ,'thirtytwo','thirtythree','thirtyfour','thirtyfive','thirtysix','thirtyseven','thirtyeight','thirtynine',...
    %         'fourty','fortyone'...
    %         ,'fortytwo','fortythree','fortyfour','fortyfive','fortysix','fortyseven','fortyeight','fortynine',...
    %         'fifty','fiftyone'...
    %         ,'fiftytwo','fiftythree','fiftyfour','fiftyfive','fiftysix','fiftyseven','fiftyeight','fiftynine',...
    %         'sixty'};
    %     signalOrder=signalOrder{1:numSignal};
    posNews=[];
    
    for signum = 1:numSignal
        strField = signalOrder{signum};
        tempPos = currentplace+1:currentplace+1+signum-1;
        posNews.(strField).pos = tempPos;
        posNews.(strField).N   = signum;
        currentplace = max(tempPos);
        posNews.SigLoc(signum) = max(tempPos);
    end
    
    shkfactorA  = currentplace+1; %14 policy F1
    shkfactorB  = currentplace+2; %15 policy F2
    
    %     end
    %             ERLog         = endShocks+1:endShocks+numSignal;
    %             endShocks=max(ElLog);
    
    %     NVarY   = currentplace+2;
    %     Neq     = currentplace+2;
    
    %% Expectation Variables
    %%
    jj=0; ii=currentplace+2;
    EpiLog=ii+1;ii=ii+1;jj=jj+1;
    EyLog=ii+1;ii=ii+1;jj=jj+1;
    ErLLog=ii+1;ii=ii+1;jj=jj+1;
    EPbLog=ii+1;ii=ii+1;jj=jj+1;
    ElambdaLog=ii+1;ii=ii+1;jj=jj+1;
    ErkLog=ii+1;ii=ii+1;jj=jj+1;
    EtaukLog=ii+1;ii=ii+1;jj=jj+1;
    EqLog=ii+1;ii=ii+1;jj=jj+1;
    EiLog=ii+1;ii=ii+1;jj=jj+1;
    EwLog=ii+1;ii=ii+1;jj=jj+1;
    
    %
    %     EpiLogc=ii+1;ii=ii+1;jj=jj+1;
    %     ErLLogc=ii+1;ii=ii+1;jj=jj+1;
    %     EPbLogc=ii+1;ii=ii+1;jj=jj+1;
    %     ElambdaLogc=ii+1;ii=ii+1;jj=jj+1;
    %     ErkLogc=ii+1;ii=ii+1;jj=jj+1;
    %     EtaukLogc=ii+1;ii=ii+1;jj=jj+1;
    %     EqLogc=ii+1;ii=ii+1;jj=jj+1;
    %     EiLogc=ii+1;ii=ii+1;jj=jj+1;
    %     EwLogc=ii+1;ii=ii+1;jj=jj+1;
    
    nend=jj;
    
    % Final Counts
    NVarY   =ii; %Lobs;
    Neq     =ii; %Lobs;
    
    %%  PART III: Position of shocks
    
    egcLog     = 1;                 %1  government consumption shock
    ezLog      = 2;                 %2  tranfer shock
    ezLRLog    = 3;                 %3  shock to the long run component of transfers
    eaLog      = 4;                 %4  technology shock
    ebLog      = 5;                 %5  preference shock
    emLog      = 6;                 %6  monetary policy shock
    eiLog      = 7;                 %7  investment specific technology shock
    ewLog      = 8;                 %8  wage markup shock
    epLog      = 9;                 %9  price markup shock
    erpLog     = 10;                %10  risk-premium shock
    epistarLog = 11;                %11  shock to the inflation drift
    evLog      = 12;                %13 Govt measurement error/fiscal shock
    factorA    = 13;                 %13 FWG target factor
    factorB    = 14;                 %14 FWG path factor
    currentplace=15;
    
    ER_Signal = currentplace:currentplace+numSignal-1; % Remember there is a "zero" signal
    if isempty(ER_Signal)
        NShocks=currentplace-1;
    else
        NShocks=ER_Signal(end);
    end
    %     NShocks=16;
    
    % Matrix of Standard Deviations
    SDX=eye(NShocks);
    
    SDX(egcLog,egcLog)              = siggc;
    SDX(ezLog,ezLog)                = sigz;
    SDX(ezLRLog,ezLRLog)            = sigzlr;
    SDX(eaLog,eaLog)                = siga;
    SDX(ebLog,ebLog)                = sigb;
    SDX(emLog,emLog)                = sigm;
    SDX(eiLog,eiLog)                = sigi;
    SDX(ewLog,ewLog)                = sigw;
    SDX(epLog,epLog)                = sigp;
    SDX(erpLog,erpLog)              = sigrp;
    SDX(epistarLog,epistarLog)      = sigpistar;
    SDX(evLog,evLog)                = sigv;
    SDX(factorA,factorA)            = FactA_STD;
    SDX(factorB,factorB)            = FactB_STD;
    
    SDX(ER_Signal,ER_Signal)    = diag(STD(2:end)); %STD(2:end)
    
    %     SDX=SDX/100;
    
    
    %%  PART IV: Model Declaration
    GAM0   = zeros(Neq,NVarY);
    %ALead   = zeros(Neq,NVarY);
    GAM1    = zeros(Neq,NVarY);
    PSI     = zeros(Neq,NShocks);
    PPI     = zeros(Neq,nend);
    CC      = zeros(Neq,1);
    %%  PART V: Steady-State
    % 5.0 Preliminaries
    %     pistar=1.005;
    Rho = (1 - (1/AD))*(1/bet);
    gamm = gamm100/100;
    expg = exp(gamm);
    Rss = expg/bet*exp(pistar100/100);
    Rbar = (Rss - 1)*100;
    Pb = 1/(Rss - Rho);  % both Pb and Rss are in nominal terms
    Rk = (exp(gamm)/bet - 1 + delt)/(1-tauk);
    psi1 = Rk*(1-tauk);
    mc = 1/(1 + etap);
    w = (mc*((1-alph)^(1-alph))*(alph^alph)*(Rk^(-alph)))^(1/(1-alph));
    KL = (w/Rk)*alph/(1-alph);
    OmegL = (KL^alph) - Rk*(KL) - w;
    YL = (KL^alph) - OmegL;
    IL = (1-(1-delt)*exp(-gamm))*expg*KL;
    CL = YL*(1 - sgc) - IL;
    rk = Rk;
    ZL = ((1 - Rss*exp(-gamm))*sb - sgc)*YL + (tauc)*CL + taul*w + tauk*rk*KL;
    % ZL = ((1-(1+Rho*Pb)/Pb/expg)*sb - sgc)*YL + (tauc)*CL + taul*w + tauk*rk*KL;
    ZnL = ZL;
    CnL = ((1-taul)*w + ZnL)/(1+tauc);
    CsL = (CL - muHH*CnL)/(1-muHH);
    CstarL = CsL + alphag*sgc*YL;
    l = ((w*(1-taul)/((1+tauc)*(1+etaw)))*(1/((1-thet*exp(-gamm))*CstarL)))^(1/(xi + 1));
    cs = CsL*l;
    cn = CnL*l;
    y = YL*l;
    k = KL*l;
    Omeg = OmegL*l;
    c = CL*l;
    inv = IL*l;
    z = ZL*l;
    b = sb*y;
    gc = sgc*y;
    ky = k/y;
    cy = c/y;
    ly = l/y;
    TK = tauk*rk*k;
    TL = taul*l*w;
    TC = tauc*c;
    S = tauk*rk*k + taul*l*w + tauc*c - gc - z;
    
    %% signal extraction
    D=[csi_a,csi_rp];
    SIG=diag([siga^2,sigrp^2]);
    K=SIG*D'*pinv(D*SIG*D'*sigv^2);
    
    %%  PART VI: Equations actual economy
    % 1) Production Function eq.22
    GAM0(1,yLog)  = 1;
    GAM0(1,kLog)  = -((y+Omeg)/y)*alph;
    GAM0(1,lLog)  = -((y+Omeg)/y)*(1-alph);
    
    % 2) Production Factors   eq.23
    GAM0(2,rkLog)  = 1;
    GAM0(2,wLog)   =-1;
    GAM0(2,kLog)   = 1;
    GAM0(2,lLog)   =-1;
    
    % 3) Marginal Cost  eq.24
    
    GAM0(3,mcLog)  =1;
    GAM0(3,rkLog)  =-alph;
    GAM0(3,wLog)   =alph-1;
    
    % 4) Price Phillips Curve
    lamprice = ((1+bet*chip)*omegap)/((1-bet*omegap)*(1-omegap)); %this is inverse of slope
    GAM0(4,piLog)       = lamprice;
    GAM0(4,mcLog)       = -1;
    GAM0(4,shkpLog)     =-lamprice;
    
    GAM1(4,piLog)        = lamprice*chip/(1+bet*chip);
    
    GAM0(4,EpiLog)       = -lamprice*bet/(1+bet*chip);
    %GAM0(4,shkpistarLog)  =-1;
    
    % 5) Household FOC for Consumption (Savers' Lagrange Multiplier) eq.25
    GAM0(5,lambdaLog) = 1;
    GAM0(5,cstarLog)  = expg/(expg-thet);
    GAM0(5,taucLog)   = (tauc/(1+tauc));
    GAM0(5,shkbLog)   =-1;
    GAM0(5,shkaLog)   = thet/(expg-thet);
    
    GAM1(5,cstarLog)  = thet/(expg-thet);
    
    % 6) Long-Run Real Interest Rate eq.46
    GAM0(6,rLLog) = 1;
    GAM0(6,PbLog) = 1;
    
    GAM0(6,ErLLog) = -bet*Rho/expg;
    GAM0(6,EPbLog) = -bet*Rho/expg;
    GAM0(6,EpiLog) = 1;
    
    
    % 7) Long-Run Inflation Rate eq.47
    GAM0(7,piLLog)  = 1;
    GAM0(7,PbLog)   = 1;
    GAM0(7,rLLog)   = 1;
    
    
    % 8) Consumption in Utility eq.26
    GAM0(8,cstarLog)  = 1;
    GAM0(8,csLog)     =-cs/(cs + alphag*gc);
    GAM0(8,gcLog)     =-alphag*gc/(cs + alphag*gc);
    
    
    % 9) Euler equation eq.27
    GAM0(9,lambdaLog)      = 1;
    GAM0(9,RLog)           =-1;
    GAM0(9,shkrpLog)       =-1;  %short-term risk premium shock
    GAM0(9,shkaLog)        = rhoa;
    
    GAM0(9,EpiLog)          = 1;
    GAM0(9,ElambdaLog)      =-1;
    
    % 10) FOC Capacity Utilization eq.29
    GAM0(10,rkLog) = ((1-gpsi)/gpsi);
    GAM0(10,vLog)  = -1;
    GAM0(10,taukLog) = -(((1-gpsi)/gpsi)*tauk/(1-tauk));
    
    % 11) FOC Capital eq.30
    GAM0(11,qLog)       =1;
    GAM0(11,RLog)       =1;
    GAM0(11,shkrpLog)   =1;  %short-term risk premium shock
    
    GAM0(11,ErkLog)      = -bet*exp(-gamm)*Rk*(1-tauk);
    GAM0(11,EtaukLog)    = tauk*exp(-gamm)*bet*Rk;
    GAM0(11,EqLog)       = -bet*exp(-gamm)*(1-delt);
    GAM0(11,EpiLog)      = -1;
    
    % 12) Investment FOC  eq.31
    GAM0(12,iLog)     = 1;
    GAM0(12,qLog)     =-1/((1+bet)*s*(exp(2*gamm)));
    GAM0(12,shkaLog)  = (1-bet*rhoa)/(1+bet);
    GAM0(12,shkiLog)  =-1;
    
    GAM1(12,iLog)      = 1/(1+bet);
    GAM0(12,EiLog)     =-bet/(1+bet);
    
    % 13) Effective Capital eq.32
    GAM0(13,kLog)       = 1;
    GAM0(13,vLog)       =-1;
    GAM0(13,shkaLog)    = 1;
    
    GAM1(13,kbarLog)     = 1;
    
    % 14) Law of Motion for Capital eq.33
    GAM0(14,kbarLog)    = 1;
    GAM0(14,shkaLog)    = (1-delt)*exp(-gamm);
    GAM0(14,shkiLog)    =-(1 - (1-delt)*exp(-gamm))*((1+bet)*s*(exp(2*gamm)));
    GAM0(14,iLog)       =-(1 - (1-delt)*exp(-gamm));
    
    GAM1(14,kbarLog)     = (1-delt)*exp(-gamm);
    
    % 15) Wage Equation eq.35
    lamwage = (omegaw*(1+bet)*(1+xi*(1+(1/etaw))))/((1-omegaw*bet)*(1-omegaw));
    GAM0(15,wLog)      = 1 + lamwage;
    GAM0(15,lLog)      =-xi;
    GAM0(15,taulLog)   = -(taul/(1-taul));
    GAM0(15,lambdaLog) = 1;
    GAM0(15,piLog)     = (lamwage*(1 + bet*chiw)/(1 + bet));
    GAM0(15,shkbLog)   =-1;
    GAM0(15,shkaLog)   = lamwage*((1 + bet*chiw - rhoa*bet)/(1+bet));
    GAM0(15,shkwLog)   =-lamwage;
    
    GAM1(15,wLog)       =(lamwage/(1+bet));
    GAM1(15,piLog)      =(lamwage*chiw/(1 + bet));
    GAM1(15,shkaLog)    =(lamwage*chiw/(1+bet));
    
    GAM0(15,EwLog)      =-lamwage*(bet/(1+bet));
    GAM0(15,EpiLog)     =-(lamwage*bet/(1+bet));
    
    % 16) Monetary Policy Rule
    GAM0(16,RLog)          = 1;
    GAM0(16,piLog)         =-(1-rhor)*phipi/4;
    GAM1(16,piLog)         =(1-rhor)*phipi/4;
    GAM1(16,piLagLog)      =(1-rhor)*phipi/4;
    GAM0(16,EpiLog)        =-(1-rhor)*phipi/4; 
    
    GAM0(16,yLog)          =-(1-rhor)*phiy;
    GAM1(16,yLog)         =(1-rhor)*phiy/4;
    GAM1(16,yLagLog)      =(1-rhor)*phiy/4;
    GAM0(16,EyLog)        =-(1-rhor)*phiy/4; 
    
    GAM0(16,shkmLog)       =-1;
    GAM0(16,shkpistarLog)  =-1;
    
    GAM1(16,RLog)           = rhor;
    
    for i = 1:numSignal
        tempStruct  = posNews.(signalOrder{i});
        temp.pos    = tempStruct.pos;
        temp.N      = tempStruct.N;
        
        GAM0(temp.pos(1),temp.pos(1)) = 1;
        
        PSI(temp.pos(1),factorA)       = Aload(i+1); %param.Structural.(ALoadings{i+1}).mean;
        PSI(temp.pos(1),factorB)       = Bload(i+1); %param.Structural.(BLoadings{i+1}).mean;
        PSI(temp.pos(1),ER_Signal(i))= 1;
        
        GAM1(16,temp.pos(end)) = 1;
        
        if i==1
            continue
        end
        
        GAM0(temp.pos(2:temp.N),temp.pos(2:temp.N))    = eye(temp.N-1);
        GAM1 (temp.pos(2:temp.N),temp.pos(1:temp.N-1))  = eye(temp.N-1);
        
    end
    
    % 17) Aggregate Resource Constraint eq.37
    GAM0(17,cLog)         = c;
    GAM0(17,iLog)         = inv;
    GAM0(17,gcLog)        = sgc*y;
    GAM0(17,vLog)         = psi1*k;
    GAM0(17,yLog)         = -y;
    
    % 18) Non-Savers Household's Budget eq.34
    GAM0(18,cnLog)        =  cn*(1+tauc);
    GAM0(18,taucLog)      =  tauc*cn;
    GAM0(18,wLog)         = -w*l*(1-taul);
    GAM0(18,lLog)         = -w*l*(1-taul);
    GAM0(18,taulLog)      =  w*l*taul;
    GAM0(18,zLog)         =  -1;
    
    % 19) Consumption Aggregation  eq.36
    GAM0(19,cLog)         = c;
    GAM0(19,csLog)        =-(1-muHH)*cs;
    GAM0(19,cnLog)        =-muHH*cn ;
    
    
    % 20) Maturity Structure eq.28 CHECK SS RELATION
    GAM0(20,RLog)        = 1;
    GAM0(20,shkrpLog)    = 1;
    GAM0(20,PbLog)       = 1;
    
    GAM0(20,EPbLog)        =-Rho*Pb/(1+Rho*Pb);
    
    
    % 21) Government Budget Constraint
    GAM0(21,bLog)         = sb;
    GAM0(21,taukLog)      = tauk*rk*ky;
    GAM0(21,rkLog)        = tauk*rk*ky;
    GAM0(21,kLog)         = tauk*rk*ky;
    GAM0(21,taulLog)      = taul*w*ly;
    GAM0(21,wLog)         = taul*w*ly;
    GAM0(21,lLog)         = taul*w*ly;
    GAM0(21,taucLog)      = tauc*cy;
    GAM0(21,cLog)         = tauc*cy;
    GAM0(21,piLog)        = sb/bet;
    GAM0(21,shkaLog)      = sb/bet;
    GAM0(21,PbLog)        =-sb*Rho*exp(-gamm);
    GAM0(21,gcLog)        =-sgc;
    GAM0(21,zLog)         =-(1/y);
    
    GAM1(21,bLog)          = sb/bet;
    GAM1(21,PbLog)         =-sb/bet;
    
    
    % 22) gc Rule
    
    GAM0(22,gcLog)          = 1;
    GAM0(22,shkgcLog)        =-1;
    
    GAM1(22,gcLog)           = rhogc;
    GAM1(22,sbLog)           =-(1-rhogc)*gammgc;
    
    % 23) Capital Tax Rate Rule
    
    GAM0(23,taukLog)     = 1;
    
    GAM1(23,taukLog)      = rhotk;
    GAM1(23,sbLog)        = (1-rhotk)*gammtk;
    
    
    % 24)  Labor Tax Rate Rule
    
    GAM0(24,taulLog)     = 1;
    
    GAM1(24,taulLog)      = rhotl;
    GAM1(24,sbLog)        = (1-rhotl)*gammtl;
    
    % 25) Consumption Tax Rate Rule
    
    GAM0(25,taucLog)     = 1;
    
    GAM1(25,taucLog)      = rhotc;
    GAM1(25,sbLog)        =(1-rhotc)*gammtc;
    
    % 26) Transfers rule
    
    GAM0(26,zLog)=1;
    GAM0(26,zlrLog)=-1;
    
    GAM0(26,shkaTLog)=(1-rhoz)*csi_a;
    GAM0(26,shkrpTLog)=-(1-rhoz)*csi_rp;
    GAM0(26,yLog)      =-phizy; 
    
    PSI(26,evLog)=(1-rhoz);
    PSI(26,ezLog)=1;
    
    GAM1(26,zLog)=rhoz;
    GAM1(26,zlrLog)=-rhoz;
    
    GAM1(26,sbLog)     =-(1-rhoz)*gammz;
    
    % 27)	Fisher Equation
    GAM0(27,rLog)        = 1;
    GAM0(27,RLog)        =-1;
    
    GAM0(27,EpiLog)       = 1;
    
    % 28)	sb Defined
    GAM0(28,sbLog)       = 1;
    GAM0(28,yLog)        = 1;
    GAM0(28,bLog)        =-1;
%     
%     % 29)  Consumption Tax Revenue
%     GAM0(29,TcLog)       = 1;
%     GAM0(29,taucLog)     =-1;
%     GAM0(29,cLog)        =-1;
%     
%     % 30)	Capital Tax Revenue
%     GAM0(30,TkLog)       = 1;
%     GAM0(30,taukLog)     =-1;
%     GAM0(30,rkLog)       =-1;
%     GAM0(30,kLog)        =-1;

    %29) Lag inflation
    GAM0(29,piLagLog)=1;
    GAM1(29,piLog)=1;
    
    %30) Lag output
    GAM0(30,yLagLog)=1;
    GAM1(30,yLog)=1;
    
    % 31)	rb defined CHECK
    GAM0(31,rbLog)       = 1;
    GAM0(31,PbLog)       =-Rho*bet/expg;
    GAM0(31,piLog)       = 1;
    
    GAM1(31,PbLog)        =-1;
%     
%     %(32)	S defined CHECK
%     GAM0(32,SLog)       = 1;
%     GAM0(32,taukLog)    =-tauk*rk*k;
%     GAM0(32,rkLog)      =-tauk*rk*k;
%     GAM0(32,kLog)       =-tauk*rk*k;
%     GAM0(32,taulLog)    =-taul*w*l;
%     GAM0(32,wLog)       =-taul*w*l;
%     GAM0(32,lLog)       =-taul*w*l;
%     GAM0(32,taucLog)    =-tauc*c;
%     GAM0(32,cLog)       =-tauc*c;
%     GAM0(32,zLog)       = 1;
%     GAM0(32,gcLog)      = gc;
%     
%     %  34)	Labor Tax Revenue
%     GAM0(34,TlLog)       = 1;
%     GAM0(34,taulLog)     =-1;
%     GAM0(34,wLog)        =-1;
%     GAM0(34,lLog)        =-1;
    
    %% Exogenous Processes
    
    % 35) Government Spending
    GAM0(32,shkgcLog) = 1;
    PSI(32,egcLog)     = 1;
    GAM1(32,shkgcLog)  = rhoeg;
     
    % 33) LR component transfers
    
    GAM0(33,shkzLRLog)       = 1;
    GAM1(33,shkzLRLog)       = rhozlr;
    PSI(33,ezLRLog)       = 1;
    
    % 34) Transfers shock
    GAM0(34,shkzLog)  = 1;
    PSI(34,ezLog)      = 1;
    GAM1(34,shkzLog)   = rhoez;
    
   
    % 35) Growth rate of Technology Shock
%     GAM0(35,shkaLog)  = 1;
%     PSI(35,eaLog)      = 1;
%     GAM1(35,shkaLog)   = rhoa;
    GAM0(35,shkaLog)  = 1;
    GAM0(35,shka0Log)= -1;
    
    GAM1(35,shka1Log)= 1;
    GAM1(35,shkaLog)   = rhoa;    
   
    % 36) Surprise risk-premium shock at time t
    GAM0(36,shka0Log)= 1;
    
    GAM1(36,shkaTLog)=1;
    GAM1(36,shka1Log)=-1;
    
    %37) Anticipated tfp shock at time t
    GAM0(37,shka1Log)=1;
    GAM0(37,shkrpTLog)=-K(1)*csi_rp;
    GAM0(37,shkaTLog)=-K(1)*csi_a;
    PSI(37,evLog)=K(2);
    
    %38) Next period's tfp shock
    GAM0(38,shkaTLog)=1;
    PSI(38,eaLog)=1;
    
    % 39) Preference Shock
    GAM0(39,shkbLog)  = 1;
    PSI(39,ebLog)      = 1;
    GAM1(39,shkbLog)   = rhob;
    
    % 40) Monetary Policy Shock
    GAM0(40,shkmLog)  = 1;
    PSI(40,emLog)      = 1;
    GAM1(40,shkmLog)   = rhoem;
    
    % 43) Investment Shock
    GAM0(41,shkiLog)  = 1;
    PSI(41,eiLog)      = 1;
    GAM1(41,shkiLog)   = rhoi;
    
    % 44) Wage Markup Shock
    GAM0(42,shkwLog)  = 1;
    PSI(42,ewLog)      = 1;
    GAM1(42,shkwLog)   = rhow;
    
    % 45) Price Markup Shock
    GAM0(43,shkpLog)  = 1;
    PSI(43,epLog)      = 1;
    GAM1(43,shkpLog)   = rhop;
    
    % 46) Risk premium Shock
    GAM0(44,shkrpLog)  = 1;
    GAM0(44,shkrp0Log)= -1;
    %PSI(36,ezLog)      = 1;
    
    GAM1(44,shkrp1Log)= 1;
    GAM1(44,shkrpLog)   = rhorp;
    
    % 47) Surprise risk-premium shock at time t
    GAM0(45,shkrp0Log)= 1;
    
    GAM1(45,shkrpTLog)=1;
    GAM1(45,shkrp1Log)=-1;
    
    %48) Anticipated risk premium shock at time t
    GAM0(46,shkrp1Log)=1;
    GAM0(46,shkrpTLog)=-K(2)*csi_rp;
    GAM0(46,shkaTLog)=-K(2)*csi_a;
    PSI(46,evLog)=K(2);
    
    %49) Next period's risk premium shock
    GAM0(47,shkrpTLog)=1;
    PSI(47,erpLog)=1;
    
    % 50) Inflation drift Shocks *
    GAM0(48,shkpistarLog)  = 1;
    PSI(48,epistarLog)      = 1;
    GAM1(48,shkpistarLog)   = rhopidrift;
   
    
    
    %% Observables
    
    % 49) Observable output growth
    GAM0(49,yobs)=1;
    GAM0(49,yLog)=-1;
    GAM0(49,shkaLog)=-1;
    
    GAM1(49,yLog)=-1;
    
    % 50) Observable consumption growth
    GAM0(50,cobs)=1;
    GAM0(50,cLog)=-1;
    GAM0(50,shkaLog)=-1;
    
    GAM1(50,cLog)=-1;
    
    %51) Observable investment growth
    GAM0(51,iobs)=1;
    GAM0(51,iLog)=-1;
    GAM0(51,shkaLog)=-1;
    
    GAM1(51,iLog)=-1;
    
    % 52) Observable real wage growth
    GAM0(52,wobs)=1;
    GAM0(52,wLog)=-1;
    GAM0(52,shkaLog)=-1;
    
    GAM1(52,wLog)=-1;
    
    % 53) Observable transfers growth
    GAM0(53,zobs)=1;
    GAM0(53,zLog)=-1;
    GAM0(53,shkaLog)=-1;
    
    GAM1(53,zLog)=-1;
    
    % 54) Government Spending Growth
    GAM0(54,gobs)=1;
    GAM0(54,gcLog)=-1;
    GAM0(54,shkaLog)=-1;
    
    GAM1(54,gcLog)=-1;
    
    %Expectations Errors
    if isempty(posNews)
        eq=54;
    else
        eq=max(posNews.SigLoc);
    end
    
    eq=eq+1;
    % IID Shocks: Policy Factors
    % 84) Factor A
    GAM0(eq,shkfactorA)=1;
    PSI(eq,factorA)=1;
    
    eq=eq+1;
    % 85) Factor B
    GAM0(eq,shkfactorB)=1;
    PSI(eq,factorB)=1;
    
    i=0;
    
    eq=eq+1;
    i=i+1;
    GAM0(eq,piLog)    = 1;
    GAM1(eq,EpiLog)   = 1;
    PPI(eq,i) = 1;
    
    eq=eq+1;
    i=i+1;
    GAM0(eq,yLog)    = 1;
    GAM1(eq,EyLog)   = 1;
    PPI(eq,i) = 1;
    
    eq=eq+1;
    i=i+1;
    GAM0(eq,PbLog)    = 1;
    GAM1(eq,EPbLog)   = 1;
    PPI(eq,i) = 1;
    
    eq=eq+1;
    i=i+1;
    GAM0(eq,rLLog)    = 1;
    GAM1(eq,ErLLog)   = 1;
    PPI(eq,i) = 1;
    
    eq=eq+1;
    i=i+1;
    GAM0(eq,lambdaLog)    = 1;
    GAM1(eq,ElambdaLog)   = 1;
    PPI(eq,i) = 1;
    
    eq=eq+1;
    i=i+1;
    GAM0(eq,rkLog)    = 1;
    GAM1(eq,ErkLog)   = 1;
    PPI(eq,i) = 1;
    
    eq=eq+1;
    i=i+1;
    GAM0(eq,taukLog)    = 1;
    GAM1(eq,EtaukLog)   = 1;
    PPI(eq,i) = 1;    
    
    eq=eq+1;
    i=i+1;
    GAM0(eq,qLog)    = 1;
    GAM1(eq,EqLog)   = 1;
    PPI(eq,i) = 1;
    
    eq=eq+1;
    i=i+1;
    GAM0(eq,iLog)    = 1;
    GAM1(eq,EiLog)   = 1;
    PPI(eq,i) = 1;
    
    eq=eq+1;
    i=i+1;
    GAM0(eq,wLog)    = 1;
    GAM1(eq,EwLog)   = 1;
    PPI(eq,i) = 1;
    
    %%  PART VII: Solve Model
    [GG,C,RR,fmat,fwt,ywt,gev,eu]=gensys(GAM0,GAM1,CC,PSI,PPI);
    flag.euok = isequal(eu(:),[1;1]);
    if isequal(eu(:),[1;1])==false
        
        % Clean
        ZZ  = [];
        Cobs= [];
        SDX = [];
        RR  = [];
        ssvec=[];
        ssnames={};
        namesstates={};
        namesshocks={};
        disp('Model has no solution')
        return
    end
    
    %% Remove Expectational Vars
    GG=GG(1:end-nend,1:end-nend); RR=RR(1:end-nend,:);
    
    %% ADD ME error for GDP growth
    [GG,RR,SDX,yobsme]=addMeasurementRow(yobs,1,STD_gdpME,GG,RR,SDX);
    
    %% ADD ME error for government bnd
    [GG,RR,SDX,sbobs]=addMeasurementRow(sbLog,1,STD_byME,GG,RR,SDX);
    
    %% ADD Expected Interest Rate
    %Expanding GG and RR to include Er
    aaa=zeros(numSignal,size(GG,2)); %bbb=zeros(numSign,size(RR,2));
    for i=1:numSignal
        aa=GG^i; %bb=RR^i;
        aaa(i,:)=aa(RLog,:); %bbb(i,:)=bb(3,:);
    end
    GG1=aaa*GG; RR1=aaa*RR;
    %     xx=size(GG,1);yy=size(RR,2);
    GG=[[GG,zeros(size(GG,1),numSignal)];[GG1,zeros(size(GG1,1),numSignal)]];
    RR=[RR;RR1];
    EFFR=size(GG,2)-numSignal+1:size(GG,2);
    %% Measurement Equations
    %inizialize Measurement Matrices
    vy=1;
    vc=2;
    vi=3;
    vh=4;
    vR=5;
    vwgr=6;
    vpi=7;
    vtr=8;
    vg=9;
    vb=10;
    vEFFR=11:10+numSignal;
    %     if isempty(vEFFR)
    %         NObs=vtr;
    %     else
    %         NObs=vEFFR(end);
    %     end
    if flagEFFR==0
        NObs=vb;
    else
        NObs=vEFFR(end);
    end
    ZZ=zeros(NObs,size(GG,1));
    Cobs=zeros(length(GG),1);
    
    %Output growth
    ZZ(vy,yobsme)=1;
    %Consumption growth
    ZZ(vc,cobs)=1;
    %Investment growth
    ZZ(vi,iobs)=1;
    % Hours
    ZZ(vh,lLog)=1;
    %Interest rate
    ZZ(vR,RLog)=1;
    %     %EFFR
    %     ZZ(vEFFR,EFFR(1:10))=eye(10);
    %Real wag growth
    ZZ(vwgr,wobs)=1;
    %Inflation
    ZZ(vpi,piLog)=1;
    %Transfer Growth Rate
    ZZ(vtr,zobs)=1;
    % Govt consumption
    ZZ(vg,gobs)=1;
    %Govt debt-to-GDP ratio
    ZZ(vb,sbobs)=1;
    if flagEFFR==1 %~isempty(vEFFR)
        ZZ(vEFFR,EFFR)=eye(numSignal);
    end
    
    Cobs(yobsme)=gamm100;
    Cobs(cobs)=gamm100;
    Cobs(iobs)=gamm100;
    Cobs(gobs)=gamm100;
    %     Cobs(vh)=l;  %hours are demeaned
    Cobs(wobs)=gamm100;
    
    Cobs(piLog)=pistar100;
    Cobs(sbobs)=log(sb)*100;
    Cobs(zobs)=gamm100;
    
    if flagEFFR==0 %isempty(vEFFR)
        Cobs(RLog)=(log(Rss))*100;
    else
        Cobs([RLog,EFFR])=(log(Rss))*100;
    end
    
    
    names.states  ={
        'consumption savers'
        'consumption: Non-Savers'
        'nominal interest rate'
        'investment'
        'effective capital'
        'capital utilization rate'
        'labor'
        'output'
        'govt consumption'
        'aggregate consumption'
        'Invest Lagrangian'
        'real return for private k'
        'real wage'
        'inflation'
        'govt debt'
        'b/y ratio'
        'tauk'
        'taul'
        'tauc'
        'real interest rate'
        'transfers total'
        'transfers adjustments'
        'real marginal cost'
        'private capital'
        'HH Lagrangian'
        'price of bonds'
        'consumption'
        'long-run inflation'
        'long-run interest rate'
        'primary surplus'
        'rb defined'
        'capital tax revenue'
        'labor tax revenue'
        'consumption tax revenue'
        % COUNTERFACTUAL ECONOMY
        'consumption savers CF'
        'consumption non-Savers CF'
        'nominal interest rate CF'
        'investment CF'
        'effective capital CF'
        'capital utilization rate CF'
        ' labor CF'
        'output CF'
        'govt consumption CF'
        'aggregate consumption CF'
        'Invest Lagrangian CF'
        'real return for private k CF'
        'real wage CF'
        'inflation CF'
        'govt debt CF'
        'b/y ratio CF'
        'tauk CF'
        'taulLog CF'
        'taucLog CF'
        'real interest rate CF'
        'transfers total CF'
        'transfers adjustments CF'
        'real marginal cost CF'
        'private capital CF'
        'HH Lagrangian CF'
        'price of bonds CF'
        'consumption in utility CF'
        'long-run inflation CF'
        'long-run interest rate CF'
        'primary surplus CF'
        'rb defined CF'
        'capital tax revenue CF'
        'labor tax revenue CF'
        'consumption tax revenue CF'
        'yobs'
        'cobs'
        'iobs'
        'gobs'
        'wobs'
        'zobs'
        'g shock'
        'tranfer shock'
        'LR tranfer shock'
        'technology shock'
        'preference shock'
        'monetary policy shock'
        'investment specific technology shock'
        'wage markup shock'
        'price markup shock'
        'risk premium shock'
        'Inflation drift shock'
        'LR g shock'
        };
    for signum = 1:numSignal
        tempStruct  = posNews.(signalOrder{signum});
        tempN       = tempStruct.N;
        
        tempNames   = cellstr([repmat(['Signal ' num2str(signum) ', Lag: '],tempN,1) num2str((1:tempN)')]);
        names.states = cat(1,names.states,tempNames);
    end
    
    Addition1 =     {        'shkfactorA'
        'shkfactorB'   };
    
    names.states = cat(1,names.states,Addition1);
    Addition2 =     {'GDPobs_me'
        'Debt-To-GDP_me' };
    names.states = cat(1,names.states,Addition2);
    names.states    = cat(1,names.states  , strcat(fillcell(numSignal,1,'EFFR '),num2str((1:numSignal)'))); % 90+numSignal - 88+2*numSignal
    
    
    
    
    names.shocks={
        'government consumption shock'
        'tranfer shock'
        'tranfer shock LR'
        'technology shock'
        'preference shock'
        'monetary policy shock'
        'investment specific technology shock'
        'wage markup shock'
        'price markup shock'
        'risk-premium shock'
        'shock to the inflation drift'
        'shock to the debt in the shadow economy'
        'FWG target factor'
        'FWG path factor'};
    
    names.shocks = cat(1,names.shocks, strcat(fillcell(numSignal,1,'FG Shock'),num2str(((1:numSignal)-1)')));  % 17:end-2
    
    Addition3={
        'ME GDP'
        'ME Debt-to-GDP Ratio'
        };
    names.shocks= cat(1,names.shocks,Addition3);
    
    %         Addition =     {'AvInf me'
    %             'Relative Price'     };
    %         names.shocks = cat(1,names.shocks,Addition);
    %
    
    
    ssvec   = [Rss gc c y inv TK TL TC z bet expg Rho rhogc b sb, taul, tauk,tauc, S,y,Rbar];
    ssnames = {'Rss', 'gc', 'c', 'y', 'inv', 'TK', 'TL', 'TC', 'z', 'bet', 'expg', 'Rho', 'rhogc', 'b', 'sb', 'taul', 'tauk','tauc', 'S','y','Rbar' };
    
    % ssvec=[];
    % ssnames={};
    
    %%  PART XI: Extras
    %% add measurement errors ?????
    %%  PART XII: Output
    if size(names.states)~=size(GG,1);
        error('Wrong number of state namhes');
    end
    
    if size(names.shocks)~=size(RR,2);
        error('Wrong number of shock names');
    end
    
    namesstates         = names.states';
    namesshocks.short   = names.shocks';
    namesshocks.long    = names.shocks';
    % keyboard
end
